import React from 'react';
import {Table} from 'antd';
import * as api from './api';
import routes from './routes';
import PropTypes from 'prop-types';
import {Link} from 'react-router-dom';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';
import {PAGINATION_OPTIONS, TABLE, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT,
    DATETIME_FORMAT, FIXED_COLUMN_WIDTH} from '../constants';
import {injectIntl, formatMessage} from './intl';
import {marketingActivityStatus, currency} from '../Enum';
import DropdownMenu from 'Shared/components/DropdownMenu';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';

export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.onChangeSort = this.onChangeSort.bind(this);
        this.state = {
            loading: false
        };
    }

    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };
    onClickAbandonBtn = id => {
        this.setState({loading: true});
        const record = this.props.list.find(d => d.id === id);
        api.abandonData(id, {rowVersion: record.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }
    onClickReportBtn = id => {
        this.setState({loading: true});
        const record = this.props.list.find(d => d.id === id);
        api.submitData(id, {rowVersion: record.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }
    onClickEffectiveBtn = id => {
        this.setState({loading: true});
        const record = this.props.list.find(d => d.id === id);
        api.takeEffectData(id, {rowVersion: record.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }
    render() {
        const {permissions, sortedColumnKey, sortedOrder, initEnum} = this.props;
        const colums = [
            {
                title: formatMessage({
                    id: 'tablePanel.column.brandCode',
                    defaultMessage: '品牌编号'
                }),
                dataIndex: 'brandCode',
                sortOrder: sortedColumnKey === 'brandCode' && sortedOrder,
                sorter: true,
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.code',
                    defaultMessage: '编号'
                }),
                dataIndex: 'code',
                sortOrder: sortedColumnKey === 'code' && sortedOrder,
                sorter: true,
                render: (text, record) => (
                    <Link key="detail" to={routes.detail.format(record.id)}>
                        {text}
                    </Link>
                )
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.dealerCode',
                    defaultMessage: '总代编号'
                }),
                dataIndex: 'dealerCode'
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.theme',
                    defaultMessage: '主题'
                }),
                dataIndex: 'theme'
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.amount',
                    defaultMessage: '总预算'
                }),
                dataIndex: 'amount',
                render: text => formatAmount(text)
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.currency',
                    defaultMessage: '币种'
                }),
                dataIndex: 'currency',
                render: text => conventEnumValueToString(currency, text)
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.startTime',
                    defaultMessage: '开始时间'
                }),
                dataIndex: 'statDate',
                render: text => formatDateTime(text, DATETIME_FORMAT)
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.endTime',
                    defaultMessage: '结束时间'
                }),
                dataIndex: 'endDate',
                render: text => formatDateTime(text, DATETIME_FORMAT)
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.status',
                    defaultMessage: '状态'
                }),
                dataIndex: 'status',
                render: text => conventEnumValueToString(marketingActivityStatus, text)
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.operation',
                    defaultMessage: '操作'
                }),
                dataIndex: 'id',
                key: 'id',
                width: FIXED_COLUMN_WIDTH,
                fixed: 'right',
                render: (text, r) => {
                    const menus = [{
                        id: PERMISSION.update,
                        children: <Link key="update" to={routes.update.format(r.id)}>{
                            formatMessage({
                                id: 'tablePanel.update',
                                defaultMessage: '编辑'
                            })
                        }</Link>,
                        hidden: initEnum.isDealerUser ? (!(hasPermissions(permissions, PERMISSION.update) &&
                        hasPermissions(r.options, PERMISSION.update))) : true,
                    }, {
                        id: PERMISSION.approve,
                        children: <Link key="approve" to={routes.approve.format(r.id)}>{
                            formatMessage({
                                id: 'tablePanel.approve',
                                defaultMessage: '审核'
                            })
                        }</Link>,
                        hidden: initEnum.isDealerUser ? true : !(hasPermissions(permissions, PERMISSION.approve) &&
                        hasPermissions(r.options, 'approve')),
                    }, {
                        id: PERMISSION.abandon,
                        children: (ref =>
                            <WrappedPopconfirm
                                key="abandon"
                                placement="topLeft"
                                onConfirm={this.onClickAbandonBtn}
                                id={r.id}
                                onVisibleChange={ref.setMenuVisible}
                                title={formatMessage({
                                    id: 'tablePanel.validate.abandon',
                                    defaultMessage: '是否确认作废？'
                                })}>
                                <a>{
                                    formatMessage({
                                        id: 'tablePanel.abandon',
                                        defaultMessage: '作废'
                                    })
                                }</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: !(hasPermissions(permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon)),
                    }, {
                        id: PERMISSION.report,
                        children: (ref =>
                            <WrappedPopconfirm
                                key="report"
                                placement="topLeft"
                                onConfirm={this.onClickReportBtn}
                                id={r.id}
                                onVisibleChange={ref.setMenuVisible}
                                title={formatMessage({
                                    id: 'tablePanel.validate.report',
                                    defaultMessage: '是否确认提报？'
                                })}>
                                <a>{
                                    formatMessage({
                                        id: 'tablePanel.report',
                                        defaultMessage: '提报'
                                    })
                                }</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: !(hasPermissions(permissions, PERMISSION.report) && hasPermissions(r.options, PERMISSION.report)),
                    }, {
                        id: PERMISSION.effective,
                        children: (ref =>
                            <WrappedPopconfirm
                                key="effective"
                                placement="topLeft"
                                onConfirm={this.onClickEffectiveBtn}
                                id={r.id}
                                onVisibleChange={ref.setMenuVisible}
                                title={formatMessage({
                                    id: 'tablePanel.validate.effective',
                                    defaultMessage: '是否确认生效？'
                                })}>
                                <a>{
                                    formatMessage({
                                        id: 'tablePanel.effective',
                                        defaultMessage: '生效'
                                    })
                                }</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: initEnum.isDealerUser ? true : !(hasPermissions(permissions, PERMISSION.effective) &&
                        hasPermissions(r.options, PERMISSION.effective)),
                    }];
                    return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
                }
            }];
        const pagination = {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        return (
            <div>
                <Table
                    className="white-space-nowrap"
                    columns={colums}
                    dataSource={this.props.list}
                    onChange={this.onChangeSort}
                    rowKey="id"
                    pagination={pagination}
                    loading={this.props.loading || this.state.loading}
                    locale={locale}
                    {...TABLE} />
            </div>
        );
    }
}

TablePanel.propTypes = {
    errorMessage: PropTypes.string.isRequired,
    list: PropTypes.array.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    refreshListData: PropTypes.func,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};

import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch} from './actions';
import {createSelector} from 'reselect';
const getInitData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const isDealerUser = initData.isDealerUser;
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        return {
            isDealerUser,
            brands
        };
    }
);
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    list: getData(state),
    initEnum: getInitData(state),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    permissions: getPermissions(state),
});

const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
    refreshListData: () => dispatch(tableSearch())
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));
